
function ajx(data){
    
    $('#preload').removeClass('hidden').addClass('visible');
    
    var defaults = {
        success: function(data){
            
            $('#'+data.id).html(data.body);
            
            $('#preload').removeClass('visible');
        }
    };
   
    $.ajax($.extend(defaults,data));
}

function ajxClick (ev){
    
    $('#preload').removeClass('hidden').removeClass('visible').addClass('visible');
    
    if(ev)
        ev.preventDefault();
        
    ajx({
        url: this.href,
        dataType: "json"
    });
        
    return false;
}

function ajaxfilemanager(field_name, url, type, win) {
    var ajaxfilemanagerurl = "/js/tiny_mce/plugins/ajaxfilemanager/ajaxfilemanager.php";
    var view = 'detail';
    switch (type) {
        case "image":
            view = 'thumbnail';
            break;
        case "media":
            break;
        case "flash":
            break;
        case "file":
            break;
        default:
            return false;
    }
    tinyMCE.activeEditor.windowManager.open({
        url: "/js/tiny_mce/plugins/ajaxfilemanager/ajaxfilemanager.php?view=" + view,
        width: 782,
        height: 440,
        inline : "yes",
        close_previous : "no"
    },{
        window : win,
        input : field_name
    });
            
}

function windowResize(){
    var main = $('#main');
    var preload = $('#preload');
/*preload.css({
        width: (main.outerWidth())+'px',
        height: (main.outerHeight())+'px'
    });*/
}

function filter(ob, fn){
    var r = {};
    var elm = true;
    for(var i in ob){
        elm = fn(i, ob[i]);
        if(elm==true)
            r[i]=ob[i];
    }
    return r;
}


String.prototype.getParam = function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '/' + '([^\/]+)').exec(this)||[,null])[1]
        );
}

String.prototype.setParam = function setURLParameter(name,value) {
    
    var url = this;
    
    if(new RegExp(""+name+"\/[^\/]?").test(url)){
        url = url.replace(new RegExp(""+name+"\/[^\/]?"), name+"/"+value);
    }else{
        url = url.replace(/\/$/,'') +"/"+ name+"/"+value;
    }
    
    return url
};

        
$(function(){
    
    $('dl').append('<div class="cls"></div>');
    
    $('#page-btn').live('click',function(ev){
        var page = $('#page-number').val();
        var count = $('#page-count').val();
        
        var p = $('#pad-pages').find('.goto'+page);
        
        if(page <= count && p!=undefined){
            window.location.assign(p.attr('href'));
        }
        
        
    }) ;  
    
 
    
    $(window).resize(function(ev){
        windowResize();
    });
    
    $( ".datepicker" ).datepicker({
        dateFormat: 'yy-mm-dd'
    });
    
    $('.ajax').live('click',ajxClick);
    
    $('.ajax-post').live('click',function(ev){
        //console.log(ev);
        ev.preventDefault();        
        ajx({
            url: this.href,
            type: "POST",
            dataType: "json",
            data: $.parseJSON($('#ajx-pdata-'+this.rel).text()),
            content:$('#ajx-pdata-'+this.rel),
            success: function(data){
                if(data&&data.status=="ok"){
                    $('#preload').removeClass('hidden').removeClass('visible').addClass('visible');
                    ajxClick.apply($('.ajax.current'),null)
                }
            }
        });
        
        return false;
    });
    $('.ajaxFilterClear').live('click',function(ev){
        if(ev)
            ev.preventDefault();
        
        var url = $.parseJSON($(this).parent().find('.hidden-data').text());
    
        location.assign(url.filterUrl);
        
        return false;
    });
        
    
        
    $('.sort .asc, .sort .desc').live('click',function(ev){
         
        $('.sort span').removeClass('active');
        $(this).addClass('active');
        
        $('.ajaxFilter').click();
         
    });
     
    $('.filterField').keydown(function(ev){
        if(ev.keyCode==13){
            $('.ajaxFilter').click();
        }
    });
     
    $('.ajaxFilter').live('click',function(ev){
        
        if(ev)
            ev.preventDefault();
        var ord = $('.sort span.active');
        
        
        var filters = $('.filterField');
        var url = $.parseJSON($(this).parent().find('.hidden-data').text());
        var filter = [];
        
         
        filters.each(function(idx,elm){
            if(this.value.toString().length>0){
                filter.push( ''+this.name+'/'+this.value);
            }
        });
        
        if(ord.length>0){
            var sort = ord.hasClass('asc')?'asc':'desc';
            var name= ord.attr('class').toString().replace(/asc|desc|active|fieldName|\s/ig,'');
            filter.push( 'order'+name+'/'+sort);
        }
        var urlAdd = $('#urlAdd');

        location.assign(url.filterUrl+'/'+filter.join('/')+''+(urlAdd.length>0&&urlAdd.val().length>0?urlAdd.val():''));
        
        
        return false;
    });
    
    $('.filterField').each(function(idx,elm){
        try{
            var data = $.parseJSON($(elm).parent().find('.hidden-data.ui-filter-value').text());
        
            $(elm).val(data.value);
        }catch(e){
            console.log(e);
        }
    });
    
    
    $('.goback').click(function(ev){
        window.history.go(-1);
    });
    try{
        $(".markItUp").markItUp(mySettings);
    }catch(e){
        console.log(e);
    }
    try{
        $('textarea.tinymce').tinymce({
            // Location of TinyMCE script
            script_url : '/js/tiny_mce/tiny_mce.js',
            elements : "ajaxfilemanager",
            file_browser_callback : "ajaxfilemanager",
            // General options
            theme : "advanced",
            plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

            // Theme options
            theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true,

            // Example content CSS (should be your site CSS)
            content_css : "/css/main-front.css",

            // Drop lists for link/image/media/template dialogs
            //template_external_list_url : "/lists/template_list.js",
            //external_link_list_url : "/lists/link_list.js",
            //external_image_list_url : "/lists/image_list.js",
            //media_external_list_url : "/lists/media_list.js",
            document_base_url : "http://konserwator24.pl/",
            relative_urls : false, 
            // Replace values for the template plugin
            template_replace_values : {
                username : "Some User",
                staffid : "991234"
            }
        });

    }catch(e){
         
    }
     
    setTimeout(function(){
        windowResize.apply(window)
    },0);
    
    var id = 'short'; // ID of your textarea (no # symbol) 
    $("a.toggle").toggle(function(){
        tinyMCE.execCommand('mceRemoveControl', false, id);
    }, function () {
            
        tinyMCE.execCommand('mceAddControl', false, id);
    });
    
});
